#include "USART.h"
#include <stdio.h>


uint8_t RX_BUF[0xFFFF];
uint16_t RX_FLAG=0;


void USART_Init(void)
{
	rcu_periph_clock_enable(RCU_GPIOA);
	rcu_periph_clock_enable(RCU_USART0);

	gpio_mode_set(GPIOA,GPIO_MODE_AF,GPIO_PUPD_PULLUP,GPIO_PIN_9);
	gpio_output_options_set(GPIOA,GPIO_OTYPE_PP,GPIO_OSPEED_50MHZ,GPIO_PIN_9);
	gpio_af_set(GPIOA,GPIO_AF_7,GPIO_PIN_9);

	gpio_mode_set(GPIOA,GPIO_MODE_AF,GPIO_PUPD_PULLUP,GPIO_PIN_10);
    // gpio_output_options_set(GPIOA,GPIO_OTYPE_PP,GPIO_OSPEED_50MHZ,GPIO_PIN_10);
	gpio_af_set(GPIOA,GPIO_AF_7,GPIO_PIN_10);
	usart_deinit(USART0);
	usart_baudrate_set(USART0,9600);
	usart_parity_config(USART0,USART_PM_NONE);
	usart_word_length_set(USART0,USART_WL_8BIT);
	usart_stop_bit_set(USART0,USART_STB_1BIT);
	usart_data_first_config(USART0,USART_MSBF_LSB);
	
	usart_transmit_config(USART0,USART_TRANSMIT_ENABLE);
	usart_receive_config(USART0,USART_RECEIVE_ENABLE);

	nvic_priority_group_set(NVIC_PRIGROUP_PRE2_SUB2);

	nvic_irq_enable(USART0_IRQn,1,1);

	usart_interrupt_enable(USART0,USART_INT_RBNE);

	usart_enable(USART0);
	
}

void send_byte(uint8_t data)
{
	usart_data_transmit(USART0,data);
	while(usart_flag_get(USART0,USART_FLAG_TBE)==RESET);	
}

void send_array(uint8_t *arr,uint8_t len)
{
	uint8_t i;
	for(i=0;i<len;i++){
	send_byte(arr[i]);
}
}


void send_string(uint8_t *string)
{
	uint8_t i;
	for(i=0;string[i] != '\0';i++){
		send_byte(string[i]);
	}

}

int fputc(int ch, FILE *f)
{
	send_byte(ch);
	return ch;
}

void USART0_IRQHandler(void)
{	
// static uint8_t p0 = 0, p1 = 0;
	if(usart_flag_get(USART0,USART_FLAG_RBNE)==SET){
		usart_flag_clear(USART0,USART_FLAG_RBNE);		
		RX_BUF[RX_FLAG]=usart_data_receive(USART0);
		RX_FLAG++;
		if(RX_FLAG==0xFFFF)RX_FLAG=0;

    }
}